<template>
    <template v-if="!item.hidden">
      <!-- 只有一个子菜单且没有子菜单时 -->
      <template v-if="hasOneShowingChild(item.children, item) && (!onlyOneChild.children || onlyOneChild.noShowingChildren)">
        <el-menu-item :index="resolvePath(onlyOneChild.path)" @click="handleClick(onlyOneChild.path)">
          <el-icon v-if="onlyOneChild.meta?.icon">
            <component :is="onlyOneChild.meta.icon" />
          </el-icon>
          <template #title>{{ onlyOneChild.meta?.title }}</template>
        </el-menu-item>
      </template>
      
      <!-- 有多个子菜单 -->
      <el-sub-menu v-else :index="resolvePath(item.path)" popper-append-to-body >
        <template #title>
          <el-icon v-if="item.meta?.icon">
            <component :is="item.meta.icon" />
          </el-icon>
          <span>{{ item.meta?.title }}</span>
        </template>
        <sidebar-item
          v-for="child in item.children"
          :key="child.path"
          :item="child"
          :base-path="resolvePath(child.path)"
        />
      </el-sub-menu>
    </template>
  </template>
  
  <script setup lang="ts">
  import { ref } from 'vue'
  import { useRouter } from 'vue-router'
  const router = useRouter()
  const props = defineProps({
    item: {
      type: Object,
      required: true
    },
    basePath: {
      type: String,
      default: ''
    }
  })
  
  const onlyOneChild = ref()
  
  function hasOneShowingChild(children = [], parent: any) {
    if (!children) children = []
    
    const showingChildren = children.filter(item => {
      if (item.hidden) return false
      onlyOneChild.value = item
      return true
    })
    
    if (showingChildren.length === 1) return true
    if (showingChildren.length === 0) {
      onlyOneChild.value = { ...parent, path: '', noShowingChildren: true }
      return true
    }
    
    return false
  }
  
  function resolvePath(routePath: string) {
  if (routePath.startsWith('/')) {
    return routePath
  }
  if (props.basePath.endsWith('/')) {
    return props.basePath + routePath
  }
  return props.basePath + '/' + routePath
}
function handleClick(path : string) {
    router.push(resolvePath(path))

}
  </script>